package com.h3c.web.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;

public class SpringContextUtil implements ApplicationContextAware {
	private static ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}
	public static ApplicationContext getContext() {
		checkApplicationContext();
		return applicationContext;
	}
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		checkApplicationContext();
		return (T) applicationContext.getBean(name);
	}
	public static <T> T getBean(Class<T> clazz) {
		checkApplicationContext();
		return (T) applicationContext.getBean(clazz);
	}
	public static String[] getBeanNames() {
		checkApplicationContext();
		return applicationContext.getBeanDefinitionNames();
	}
	private static void checkApplicationContext() {
		Assert.notNull(applicationContext, "applicaitonContext not injected SpringContextUtil");
	}
}
